package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.dto.CategoryDto;
import com.sky.dto.CategoryQueryPageDto;
import com.sky.entity.Category;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/category")
@Slf4j
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;
    /**
     * 分类的分页查询
     * @param categoryQueryPageDto
     * @return
     */
    @GetMapping("/page")
    public Result<PageResult<Category>> page(CategoryQueryPageDto categoryQueryPageDto){
        log.info("{}",categoryQueryPageDto.toString());
        PageResult<Category> result =categoryService.queryPage(categoryQueryPageDto);
        return Result.success(result);
    }
    /**
     * 新增分类
     * @param categoryDto
     * @return
     */
    @CacheEvict(value = "categoryCache",allEntries = true)
    @PostMapping
    public Result<String> insert(@RequestBody CategoryDto categoryDto){
        log.info("{}",categoryDto.toString());
        categoryService.insert(categoryDto);
        return Result.success("新增分类成功");
    }

    /**
     * 更具分类类型查询
     * @param type
     * @return
     */
    @GetMapping("/list")
    public Result<List<Category>> listByType(@RequestParam(value = "type")String type){
        log.info("{}",type);
        List<Category> categoryList= categoryService.listByType(type);
        if (!categoryList.isEmpty()){
            return Result.success(categoryList);
        }else {
           return Result.error(MessageConstant.BACKGROUND_SYSTEM_ERROR);
        }
    }

    /**
     * 修改分类状态
     * @param status :状态
     * @param id :主键
     * @return :返回空值
     */
    @CacheEvict(value = "categoryCache",allEntries = true)
    @PostMapping("/status/{status}")
    public Result<String> modifyStatus(@PathVariable(value = "status")String status,String id){
       // log.info("{},{}",status,id);
        categoryService.modifyStatus(status,id);
        return Result.success("修改分类状态成功");
    }

    /**
     * 修改分类的业务
     * @param categoryDto :接收的数据对象
     * @return
     */
    @CacheEvict(value = "categoryCache",allEntries = true)
    @PutMapping
    public Result<String> modifyCategory(@RequestBody CategoryDto categoryDto){
        categoryService.modify(categoryDto);
        return Result.success("修改成功");
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @CacheEvict(value = "categoryCache",allEntries = true)
    @DeleteMapping
    public Result<String> deleteCategory(Long id){
       // log.info("{}",id);
        categoryService.removeById(id);
        return Result.success("删除成功!");
    }
}
